package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * 类描述：
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    @Override
    public User login(UserLoginDTO userLoginDTO){
        //1.调用微信第三方接口生成openid
        HashMap<String,String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",userLoginDTO.getCode());
        map.put("grant_type","authorization_code");
        //调用接口，会返回json格式字符串
        String jsonResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);

        JSONObject jsonObject = JSON.parseObject(jsonResult);//把json字符串转为json对象
        String openid = jsonObject.getString("openid");//获取json对象中的openid属性
        //2.1如果openid为空，表示登录失败，抛出异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //2.2如果openid不为空，根据openid查询user表，判断该用户是否存在（是否首次登录）
        User user = userMapper.getByOpenid(openid);
        //3.1.如果user为null，数据库不存在此openid的用户信息，则表示该用户是首次登录，将此用户信息存入数据库，并返回给前端
        if(user == null){
            User u =User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(u);
            return u;
        }
        //3.2.如果user不为null，说明数据库存在此openid的用户信息，则表示该用户不是首次登录，直接返回给前端
        return user;
    }
}
